package edu.sandau.app.basic.controller;

import edu.sandau.app.basic.domain.Cart;
import edu.sandau.app.basic.golbal.GlobalEnum;
import edu.sandau.app.basic.service.CartService;
import edu.sandau.app.basic.service.SysUserService;
import edu.sandau.app.basic.service.DishService;
import edu.sandau.app.basic.vo.BasicMsg;
import edu.sandau.app.basic.vo.BasicMsgWithData;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/cart")
@Tag(name = "购物车管理", description = "购物车管理接口")
public class CartController {
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private DishService dishService;
    
    // 获取指定用户的购物车
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取指定用户的购物车")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": [
                            {
                              "cartId": 1,
                              "userId": 1,
                              "dishId": 1,
                              "quantity": 2
                            }
                          ]
                        }"""),
                    @ExampleObject(name = "购物车为空", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": []
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "CART_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<List<Cart>> getUserCart(@PathVariable Long userId) {
        BasicMsgWithData<List<Cart>> msg = new BasicMsgWithData<>();
        try {
            List<Cart> carts = cartService.getUserCart(userId);
            if (carts != null && !carts.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("查询成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
                msg.setData(carts);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.CART_EMPTY);
                msg.setErrorMsg("购物车为空");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                msg.setData(null);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.CART_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            msg.setData(null);
        }
        return msg;
    }
    
    // 添加商品到购物车
    @PostMapping
    @Operation(summary = "添加商品到购物车")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "添加成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "添加到购物车成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "用户ID不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户ID不能为空",
                          "errorCode": "CART_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "菜品ID不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "菜品ID不能为空",
                          "errorCode": "CART_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "数量验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "数量必须大于等于1",
                          "errorCode": "CART_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "用户不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户不存在",
                          "errorCode": "CART_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "菜品不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "菜品不存在",
                          "errorCode": "CART_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "多个验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户ID不能为空; 菜品ID不能为空; 数量必须大于等于1",
                          "errorCode": "CART_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "用户和菜品验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户不存在; 菜品不存在",
                          "errorCode": "CART_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "用户和数量验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户不存在; 数量必须大于等于1",
                          "errorCode": "CART_ADD_FAIL"
                        }"""),
                    @ExampleObject(name = "添加失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "添加到购物车失败",
                          "errorCode": "CART_ADD_FAIL"
                        }""")
                }))
    })
    public BasicMsg addToCart(@RequestBody Cart cart) {
        BasicMsg msg = new BasicMsg();
        try {
            // 验证所有字段和业务逻辑，收集所有错误
            StringBuilder validationErrors = new StringBuilder();
            
            // 1. 用户相关验证（优先级最高）
            if (cart.getUserId() == null) {
                validationErrors.append("用户ID不能为空; ");
            } else {
                // 只有在用户ID不为空时才验证用户存在性
                if (sysUserService.getUserById(cart.getUserId()) == null) {
                    validationErrors.append("用户不存在; ");
                }
            }
            
            // 2. 菜品相关验证（优先级第二）
            if (cart.getDishId() == null) {
                validationErrors.append("菜品ID不能为空; ");
            } else {
                // 只有在菜品ID不为空时才验证菜品存在性
                if (dishService.getDishById(cart.getDishId()) == null) {
                    validationErrors.append("菜品不存在; ");
                }
            }
            
            // 3. 数量相关验证（优先级最低）
            if (cart.getQuantity() == null || cart.getQuantity() < 1) {
                validationErrors.append("数量必须大于等于1; ");
            }
            
            // 如果有任何验证错误，返回所有错误（单个或多个）
            if (validationErrors.length() > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.CART_ADD_FAIL);
                msg.setErrorMsg(validationErrors.toString().trim());
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 系统字段由服务层设置，不需要客户端传递
            cart.setCartId(null);
            cart.setCreateTime(null);
            cart.setUpdateTime(null);
            
            int result = cartService.addToCart(cart);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("添加到购物车成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.CART_ADD_FAIL);
                msg.setErrorMsg("添加到购物车失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.CART_ADD_FAIL);
            msg.setErrorMsg("添加到购物车失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 更新购物车商品数量
    @PutMapping("/{id}")
    @Operation(summary = "更新购物车商品数量")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "更新成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "购物车更新成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "用户ID不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户ID不能为空",
                          "errorCode": "CART_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "菜品ID不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "菜品ID不能为空",
                          "errorCode": "CART_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "数量验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "数量必须大于等于1",
                          "errorCode": "CART_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "用户不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户不存在",
                          "errorCode": "CART_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "菜品不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "菜品不存在",
                          "errorCode": "CART_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "多个验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户ID不能为空; 菜品ID不能为空; 数量必须大于等于1",
                          "errorCode": "CART_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "用户和菜品验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户不存在; 菜品不存在",
                          "errorCode": "CART_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "更新失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "购物车更新失败",
                          "errorCode": "CART_MODIFY_FAIL"
                        }""")
                }))
    })
    public BasicMsg updateCartItem(@PathVariable Long id, @RequestBody Cart cart) {
        BasicMsg msg = new BasicMsg();
        try {
            // 验证所有字段和业务逻辑，收集所有错误
            StringBuilder validationErrors = new StringBuilder();
            
            // 1. 用户相关验证（优先级最高）
            if (cart.getUserId() == null) {
                validationErrors.append("用户ID不能为空; ");
            } else {
                // 只有在用户ID不为空时才验证用户存在性
                if (sysUserService.getUserById(cart.getUserId()) == null) {
                    validationErrors.append("用户不存在; ");
                }
            }
            
            // 2. 菜品相关验证（优先级第二）
            if (cart.getDishId() == null) {
                validationErrors.append("菜品ID不能为空; ");
            } else {
                // 只有在菜品ID不为空时才验证菜品存在性
                if (dishService.getDishById(cart.getDishId()) == null) {
                    validationErrors.append("菜品不存在; ");
                }
            }
            
            // 3. 数量相关验证（优先级最低）
            if (cart.getQuantity() == null || cart.getQuantity() < 1) {
                validationErrors.append("数量必须大于等于1; ");
            }
            
            // 如果有任何验证错误，返回所有错误（单个或多个）
            if (validationErrors.length() > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.CART_MODIFY_FAIL);
                msg.setErrorMsg(validationErrors.toString().trim());
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 设置要更新的购物车ID，系统时间字段由服务层处理
            cart.setCartId(id);
            cart.setCreateTime(null); // 创建时间不允许更新
            cart.setUpdateTime(null); // 更新时间由服务层自动设置
            
            int result = cartService.updateCartItem(cart);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("购物车更新成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.CART_MODIFY_FAIL);
                msg.setErrorMsg("购物车更新失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.CART_MODIFY_FAIL);
            msg.setErrorMsg("购物车更新失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 从购物车删除商品
    @DeleteMapping("/{id}")
    @Operation(summary = "从购物车删除商品")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "删除成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "删除成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "删除失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "删除失败",
                          "errorCode": "CART_DELETE_FAIL"
                        }"""),
                    @ExampleObject(name = "系统错误", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "删除失败: 具体错误信息",
                          "errorCode": "CART_DELETE_FAIL"
                        }""")
                }))
    })
    public BasicMsg deleteCartItem(@PathVariable Long id) {
        BasicMsg msg = new BasicMsg();
        try {
            int result = cartService.deleteCartItem(id);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("删除成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.CART_DELETE_FAIL);
                msg.setErrorMsg("删除失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.CART_DELETE_FAIL);
            msg.setErrorMsg("删除失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 清空用户购物车
    @DeleteMapping("/user/{userId}")
    @Operation(summary = "清空用户购物车")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "清空成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "购物车已清空，删除了 3 项",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "购物车已空", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "购物车已清空，删除了 0 项",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "系统错误", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "清空购物车失败: 具体错误信息",
                          "errorCode": "CART_DELETE_FAIL"
                        }""")
                }))
    })
    public BasicMsg clearUserCart(@PathVariable Long userId) {
        BasicMsg msg = new BasicMsg();
        try {
            int result = cartService.clearUserCart(userId);
            msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
            msg.setErrorMsg("购物车已清空，删除了 " + result + " 项");
            msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.CART_DELETE_FAIL);
            msg.setErrorMsg("清空购物车失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
}
